package com.analyse.stock.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.constant.ApiConstant;
import com.analyse.stock.constant.StockConstant;
import com.analyse.stock.mapper.StockExchangeMapper;
import com.analyse.stock.model.StockExchangeModel;
import com.analyse.stock.service.IStockExchange;
import com.analyse.stock.utils.HttpUtil;
import com.analyse.stock.utils.StockStringUtil;
import com.analyse.stock.vo.StockExchangeVO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StockExchangeService extends ServiceImpl<StockExchangeMapper, StockExchangeModel> implements IStockExchange {

    @Override
    public Integer getAllStockExchange(String countryCode) {
        String url = ApiConstant.EXCHANGE_URL;
        if(StringUtils.isNotBlank(countryCode)){
            url = String.format(url+"&country_code={}",countryCode);
        }
        String result = HttpUtil.sendGet(url,"application/json", StockConstant.UTF8,6000L);
        if(StringUtils.isBlank(result)){
            log.info("## 没有获取到 交易所清单数据: {}-----",result);
            return 0;
        }
        JSONObject object = JSON.parseObject(result);
        if(object.getInteger("code") != 200 || StringUtils.isBlank(object.getString("data"))){
            return 0;
        }
        List<StockExchangeVO> dataList = StockStringUtil.getArray(object.getString("data"), StockExchangeVO.class);
        List<StockExchangeModel> models = dataList.stream().map(StockExchangeModel::transStockExchangeModel).collect(Collectors.toList());

        Set<String> codes = models.stream().map(StockExchangeModel::getExchangeCode).collect(Collectors.toSet());
        LambdaUpdateWrapper<StockExchangeModel> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.in(StockExchangeModel::getExchangeCode,codes);
        super.remove(queryWrapper);

        super.saveBatch(models);
        log.info("## 获取到 交易所清单数据: {} 条-----",models.size());
        return models.size();
    }

    @Override
    public StockExchangeModel getStockExchange(String countryCode,String exchangeCode) {
        LambdaUpdateWrapper<StockExchangeModel> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(StockExchangeModel::getExchangeCode,exchangeCode);
        queryWrapper.eq(StockExchangeModel::getCountryCode,countryCode);
        List<StockExchangeModel> list = super.list(queryWrapper);
        if(CollUtil.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }
}
